import { flipCardData, FlipService } from "@/popup/services/flip";
import { ava_base_url } from "@/popup/utils";
import { Button, DatePicker, Form, Input, Select, Table, Tooltip } from "antd";
import React, { useEffect, useState } from "react";
import dayjs from "dayjs";
import "./style.less";
import { RedoOutlined } from "@ant-design/icons";
import { DetailModal } from "./DetailModal";
import { useUserStore } from "@/popup/stores/user";

const Flip: React.FC = () => {
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(8);
  const [current, setCurrent] = useState(1);
  const [groupedDataById, setGroupedDataById] = useState<Record<
    string,
    flipCardData
  > | null>(null);
  const [dataSource, setDataSource] = useState([]);
  const [form] = Form?.useForm();
  const [detail, setDetail] = useState<any>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentFilters, setCurrentFilters] = useState<any>({});
  const { userInfo } = useUserStore();
  const handleDetail = (detail: any) => {
    setDetail(detail);
    setDetailVisible(true);
  };
  const columns = [
    {
      title: "成员",
      dataIndex: "xoxNickname",
      key: "xoxNickname",
      width: 130,
      render: (_: string, record: any) => {
        return (
          <div>
            <img
              width={16}
              height={16}
              src={`${ava_base_url}${record?.baseUserInfo?.avatar}`}
              alt="avatar"
            />
            <span style={{ marginLeft: "4px" }}>
              {record?.baseUserInfo?.nickname}
            </span>
          </div>
        );
      },
    },
    {
      title: "问题",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text} placement="topLeft">
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: "发送时间",
      dataIndex: "qtime",
      key: "qtime", 
      width: 130,
      render: (text: string) => <span>{dayjs(Number(text)).format("YYYY-MM-DD")}</span>,
    },
    {
      title: "消费🍗",
      dataIndex: "cost",
    },
    {
      title: "详情",
      
      dataIndex: "detail",
      //@ts-ignore
      render: (_, record) => (
        <Button
          type="link"
          onClick={() => {
            handleDetail(record);
          }}
        >
          详情
        </Button>
      ),
    },
  ];
  useEffect(() => {
    reset();
    chrome.storage.local.get("groupedDataById", (result) => {
      setGroupedDataById(result.groupedDataById || null);
    });
  }, []);

  const reset = () => {
    form?.resetFields();
    setCurrent(1);
    setCurrentFilters({});
    FlipService.getDataSourcePage({
      pageSize,
      pageNum: current,
    }, userInfo?.userInfo?.userId).then((res) => {
      setDataSource(res.data);
      console.log(res.data)
      setTotal(res.total);
    });
  };

  const handleTableChange = (pagination: any) => {
    setCurrent(pagination.current);
    setPageSize(pagination.pageSize);
    
    const requestParams = {
      pageSize: pagination.pageSize,
      pageNum: pagination.current,
      ...currentFilters
    };
    
    FlipService.getDataSourcePage(requestParams, userInfo?.userInfo?.userId).then((res) => {
      setDataSource(res.data);
      setTotal(res.total);
    });
  };

  const onFinish = (values: any) => {
    setPageSize(8);
    setCurrent(1);
    setTotal(0);
    const { member, status, dateRange, keyword } = values || {};
    
    const filters = {
      xoxId: member,
      status,
      keyword,
      startTimeMs: dateRange?.[0]?.valueOf(),
      endTimeMs: dateRange?.[1]?.valueOf(),
    };
    setCurrentFilters(filters);
    
    FlipService.getDataSourcePage({
      pageSize: pageSize,
      pageNum: current,
      ...filters
    }, userInfo?.userInfo?.userId).then((res) => {
      setDataSource(res.data);
      setTotal(res.total);
    });
  };
  return (
    <div>
      <div className="custom-form-filter-container">
        <Form form={form} layout={"inline"} onFinish={onFinish}>
          <Form.Item label="成员" name="member">
            <Select
              allowClear={true}
              options={Object.keys(groupedDataById || {})?.map((item) => ({
                label: groupedDataById?.[item]?.xoxNickname,
                value: item,
              }))}
              style={{ width: 135 }}
            />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              allowClear={true}
              options={[
                {
                  label: "已回复",
                  value: 2,
                },
                {
                  label: "进行中",
                  value: 1,
                },
                {
                  label: "已退回",
                  value: 3,
                },
              ]}
              style={{ width: 120 }}
            />
          </Form.Item>
          <Form.Item label="关键词" name="keyword">
            <Input allowClear={true} style={{ width: 120 }} size="small" />
          </Form.Item>
          <Form.Item label="时间" name="dateRange">
            <DatePicker.RangePicker allowClear={true} style={{ width: 240 }} />
          </Form.Item>
          <Form.Item name="submit">
            <Button type="primary" htmlType="submit" >
              提交
            </Button>
          </Form.Item>
          <Form.Item name="reset">
            <Tooltip title="重置">
              <RedoOutlined
                color="blue"
                onClick={reset}
                style={{ cursor: "pointer" }}
              />
            </Tooltip>
          </Form.Item>
        </Form>
      </div>
      <Table
        className="custom-extension-flip-table"
        dataSource={dataSource}
        columns={columns}
        pagination={{
          current,
          pageSize,
          total,
          showSizeChanger: false,
          showQuickJumper: false,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }}
      />
      <DetailModal
        detailVisible={detailVisible}
        setDetailVisible={setDetailVisible}
        detail={detail}
      />
    </div>
  );
};

export default Flip;
